<template>
  <vxe-form
    ref="formRef"
    :border="border"
    :title-background="titleBackground"
    vertical-align="center"
    title-width="100"
    :rules="formRules"
    :data="formData"
  >
    <vxe-form-group span="24" :title="woType" title-bold vertical>
      <vxe-form-item title="条码" field="scanBarcode" span="12">
        <template #default="{ data }">
          <vxe-input
            ref="myInput"
            v-model="formData.scanBarcode"
            clearable
            type="text"
            suffix-icon="vxe-icon-zoom-out"
            @keydown.enter="inputEnter(data.scanBarcode)"
          ></vxe-input>
        </template>
      </vxe-form-item>

      <vxe-form-item
        title="工序"
        field="proceduresName"
        span="6"
      ></vxe-form-item>
      <vxe-form-item
        title="设备"
        field="equipmentId"
        span="6"
        key="equipmentId"
      >
        <template #default="{ data }">
          <vxe-select
            v-model="formData.equipmentId"
            v-bind="equipmentOptions"
          ></vxe-select>
        </template>
      </vxe-form-item>

      <vxe-form-item title="工单" field="workNo" span="6"></vxe-form-item>

      <vxe-form-item title="工单状态" field="status" span="6" key="status">
        <span>{{ formData.status }}</span>

        <vxe-icon
          v-if="formData.status == '未开工'"
          name="bell-fill"
          status="error"
        ></vxe-icon>

        <vxe-icon
          v-else-if="formData.status == '已暂停'"
          name="bell-fill"
          status="warning"
        ></vxe-icon>

        <vxe-icon
          v-else="formData.status == '已完工'"
          name="bell-fill"
          status="success"
        ></vxe-icon>

        <!-- <vxe-select v-model="formData.teamId" v-bind="teamOptions"></vxe-select> -->
      </vxe-form-item>
      <vxe-form-item title="操作人员" field="createBy" span="6">
      </vxe-form-item>
      <vxe-form-item
        title="备注"
        field="remark"
        span="6"
        :item-render="{ name: 'VxeInput' }"
      ></vxe-form-item>

      <vxe-form-item title="物料编号" field="materialCode" span="6">
      </vxe-form-item>
      <vxe-form-item
        title="物料名称"
        field="materialName"
        span="6"
      ></vxe-form-item>
      <vxe-form-item title="数量" field="qty" span="6"></vxe-form-item>
      <vxe-form-item
        title="计划完成时间"
        field="planEndTime"
        :title-width="140"
        span="6"
      ></vxe-form-item>
    </vxe-form-group>
  </vxe-form>
</template>
<script>
import { VxeUI } from "vxe-pc-ui";
import {
  getWorkOrderByPage,
  addWorkOrder,
  delWorkOrder,
} from "@/api/product/workOrder";
import emitter from "@/utils/eventMitt";
import {
  addProceduresEquipmentConfigs,
  getProceduresEquipmentConfigByPage,
  getEquipAndProceduresByWo,
} from "@/api/baseData/proceduresEquipmentConfig";
import { getUserNameByTeamId } from "@/api/baseData/team";
import useUserStore from "@/store/modules/user";
import XEUtils, { first } from "xe-utils";
export default {
  name: "workOrder",
  props: {
    woType: {
      type: String,
      default: () => {
        return "";
      },
    },
    formDataUpdate: {
      type: Object,
      default: () => {
        return {
          scanBarcode: "",
          workstationId: "", //工位信息
          workNo: "", //工单信息
          proceduresName: "工序信息",
          equipmentId: "",
          teamId: "",
          worker: "",
          createBy: useUserStore().name,
          remark: "",
          rawMaterial: "",
          rollNums: "",
          materialCode: "",
          materialName: "",
          weight: "",
          planEndTime: "",
          status: "",
          maxCount: 0,
        };
      },
    },
    teamOptionsUpdate: {
      type: Object,
      default: () => {
        return {
          loading: false,
          placeholder: "默认最后一条",
          defaultConfig: {
            selectMode: "last",
          },
        };
      },
    },
    equipmentOptionsUpdate: {
      type: Object,
      default: () => {
        return {
          loading: false,
          placeholder: "默认最后一条",
          defaultConfig: {
            selectMode: "last",
          },
          options: [],
        };
      },
    },
  },
  // watch: {
  //   woType: {
  //     immediate: true,
  //     deep: true,
  //     handler(val, oldVal) {
  //       this.woType = val;
  //     },
  //   },
  // },
  data() {
    const opts1 = [];
    const opts2 = [];
    const teamId = null;

    const formRules = {
      scanBarcode: [{ required: true, message: "必须填写" }],
      workstationId: [{ required: true, message: "必须填写" }],
      workNo: [
        {
          required: true,
          pattern: "\\d{2}-\\d{5}",
          message: "字母开头5~10位数",
        },
      ],
      // teamId: [{ required: true, message: "必须填写" }],
      rawMaterial: [{ required: true, message: "必须填写" }],
      // rawMaterial: [
      //   {
      //     required: true,
      //     pattern: "^[a-zA-Z]\\w{5,7}$",
      //     message: "字母开头5~10位数",
      //   },
      // ],
      // role: [{ required: true, message: "必须填写" }],
    };
    const remoteConfig2 = {};
    return {
      formRules,
      border: true,
      titleBackground: false,
      formData: this.formDataUpdate,
      opts1,
      opts2,
      equipmentOptions: this.equipmentOptionsUpdate,
      teamOptions: this.teamOptionsUpdate,
      remoteConfig2,
      teamId,
      maxCount: this.formDataUpdate.maxCount,
      // woType: this.woType,
    };
  },
  async created() {
    this.remoteConfig2 = {
      queryMethod: async ({ searchValue }) => {
        /**
         * 如果班组人员不够
         */
        if (null == this.formData.teamId || "" == this.formData.teamId) {
          VxeUI.modal.message({
            content: "请先选择班组",
            status: "warning",
          });
          return;
        }
        const result = await getUserNameByTeamId({
          total: 2,
          pageSize: 10,
          currentPage: 1,
          id: this.formData.teamId,
        });
        this.opts2 = result.data;
      },
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.myInput.focus();
    });
  },
  methods: {
    async addEvent() {
      const $grid = this.$refs.gridRef2.$refs.gridRef2;
      if (this.formData.workNo == "" || this.formData.workNo == undefined) {
        VxeUI.modal.message({
          content: "请先输入工单信息",
          status: "error",
        });
      } else {
        if ($grid) {
          const record = {
            rawCode: ``,
            wo: this.formData.workNo,
            qty: 1,
            status: "未消耗",
            active: "",
          };
          const { row: newRow } = await $grid.insert(record);
          // 激活不自动聚焦
          $grid.setEditRow(newRow);

          // 激活并自动聚焦
          // $grid.setEditRow(newRow, 'name')
          // 激活并自动聚焦
          // $grid.setEditCell(newRow, 'name')
        }
      }
    },
    async saveEvent() {
      const $grid = this.$refs.gridRef2.$refs.gridRef2;
      console.log($grid, "-----$grid---");
      if ($grid) {
        const insertRecords = $grid.getInsertRecords();
        const result = await addWoRaws(insertRecords);
        $grid.commitProxy("reload");
        // VxeUI.modal.alert(`新增：${insertRecords.length} 行`);
      }
    },
    async inputEnter(params) {
      let paras = params.split("@");
      if (paras.length < 4) {
        VxeUI.modal.message({ content: "需要包含四个@", status: "error" });
      } else {
        //订单@物料@数量@开工日期@完工日期
        try {
          const result = await addWorkOrder({
            wo: paras[0],
            qty: paras[2],
            type: this.woType,
            materialCode: paras[1],
            planStartTime: paras[3],
            planEndTime: paras[4],
          });
          console.log("====>result===", result);

          const result2 = await getEquipAndProceduresByWo({
            sequence: result.data.proceduresNum,
            woType: this.woType,
          });
          this.formData.workNo = paras[0];
          this.formData.materialCode = paras[1];
          this.formData.qty = paras[2];
          this.formData.planEndTime = paras[4];
          //  this.formData.rawMaterial = paras[1]
          this.equipmentOptions.options =
            result2.data.equipmentConfigVoList.map((item) => {
              return { label: item.name, value: item.id };
            });
          this.processRelVo = result2.data.processRelVo;

          this.teamOptions.options = result2.data.teamVoList.map((item) => {
            return { label: item.name, value: item.id };
          });

          this.formData.proceduresName = this.processRelVo.proceduresName;
          // localStorage.setItem("MES_COAT_WO", JSON.stringify(paras[0]));
          // console.log("保存成功", JSON.stringify(this.formOptions.data));
          VxeUI.modal.message({ content: "保存成功", status: "success" });
          // const $grid = this.$refs.gridRef.commitProxy("reload");
          this.loading = false;
          this.showPopup = false;

          // debugger;
          console.log(this.formData.workNo, "===> this.formData.workNo");
          this.formData.scanBarcode = "";
        } catch (error) {
          this.loading = false;
        } finally {
          /**
           * mitt使用
           */
          emitter.emit("workOrder", this.formData);
          // const $grid =
          //   this.$refs.gridRef2.$refs.gridRef2.commitProxy("reload");
        }
      }
    },
  },
};
</script>
